package com.sgb.jicai.view.adapter;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.jicai.R;
import com.sgb.jicai.databinding.ItemLayoutOfferJibaojicaiBinding;
import com.sgb.jicai.databinding.ItemParticipationOfferListBinding;
import com.swgk.core.BR;
import com.swgk.core.util.TimeUtil;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.jicai.entity.OfferGroupBuyingDetailsEntity;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter2;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.MToast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 参与报价页面，参与报价列表适配器
 */
public class ParticipationOfferListAdapter extends BaseRecycleAdapter2<OfferGroupBuyingDetailsEntity.GroupBuyingDetails> {

    private int type;
    //集采类型(1是即报即采, 2是汇集采购, 3是企业专项)
    private String groupBuyType;
    private Context context;
    private TextView tvShowmore;
    private TextView tvDescribe;
    private ItemCallBack itemCallBack;
    private long deadline;
    private Calendar selectedDate = Calendar.getInstance();
    private Calendar dayCalendar = Calendar.getInstance();
    String tempDateTime = "";

    public ParticipationOfferListAdapter(Context context, List<OfferGroupBuyingDetailsEntity.GroupBuyingDetails> datas, String groupBuyType, int type) {
        super(context, R.layout.item_participation_offer_list, datas);
        this.context = context;
        this.groupBuyType = groupBuyType;
        this.type = type;
    }

    @Override
    public void convert(ItemViewHolder holder, OfferGroupBuyingDetailsEntity.GroupBuyingDetails entity, int position) {
        holder.setBinding(BR.viewModel, entity);
        tvShowmore = ((ItemParticipationOfferListBinding) holder.getmBinding()).tvShowmore;
        tvDescribe = ((ItemParticipationOfferListBinding) holder.getmBinding()).tvDescribe;
        TextView tvparam = holder.itemView.findViewById(R.id.specifications_models);//规格型号
        LinearLayout llMaterials = holder.itemView.findViewById(R.id.ll_materials);
        if (entity.getShoptype()==1){
            llMaterials.setVisibility(View.VISIBLE);
        }else {
        llMaterials.setVisibility(View.GONE);
        }
        if (entity.getAttrs() != null && entity.getAttrs().size() > 0) {
            StringBuilder stringattr = new StringBuilder();
            for (OfferGroupBuyingDetailsEntity.AttrsBean attrBean : entity.getAttrs()) {
                if (!TextUtils.isEmpty(attrBean.getValue())) {
                    stringattr.append(attrBean.getName()).append(":").append(attrBean.getValue()).append(" ");
                }
            }
            if (!TextUtils.isEmpty(stringattr.toString())) {
                tvparam.setText(stringattr.toString());
            } else {
                tvparam.setText("无");
            }
        } else {
            tvparam.setText("无");
        }

        tvShowmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvDescribe.setMaxLines(999);
            }
        });

        try {
            //获取省略的字符数，0表示没和省略
            int ellipsisCount = tvDescribe.getLayout().getEllipsisCount(tvDescribe.getLineCount() - 1);
            tvDescribe.getLayout().getEllipsisCount(tvDescribe.getLineCount() - 1);
            //ellipsisCount>0说明没有显示全部，存在省略部分。
            if (ellipsisCount > 0) {
                //展示全部，按钮设置为点击收起。
                tvShowmore.setVisibility(View.VISIBLE);
            } else {
                tvShowmore.setVisibility(View.GONE);
            }
        } catch (Exception e) {
        }
        setJibaojicaiView(holder, entity, position);
    }

    /**
     * 初始化既报既采布局
     *
     * @param holder
     * @param entity
     * @param position
     */
    private void setJibaojicaiView(ItemViewHolder holder, OfferGroupBuyingDetailsEntity.GroupBuyingDetails entity, int position) {
        ItemLayoutOfferJibaojicaiBinding jibaojicai = ((ItemParticipationOfferListBinding) holder.getmBinding()).itenJibaojicai;
        jibaojicai.viewJibaojicai.setVisibility(View.VISIBLE);
        if (position == getCount() - 1) {
            jibaojicai.vLine.setVisibility(View.GONE);
        } else {
            jibaojicai.vLine.setVisibility(View.VISIBLE);
        }

        // 设置二级列表
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.shape_list_divide_joinin_details_jc));
        ParticipationOfferSecondAdapter offerAdapter = new ParticipationOfferSecondAdapter(context, R.layout.item_participation_offer_second_category, deadline, groupBuyType,entity.getUnitName());
        offerAdapter.setItemCallBack(new ParticipationOfferSecondAdapter.ItemCallBack() {
            @Override
            public void goPriceRole(OfferGroupBuyingDetailsEntity.GroupBuyingDetails data, int index) {
                if (entity.getDetails().size() == 1) {
                    ToastUtil.show(context, "1条数据不可移除");
                    return;
                }
                entity.getDetails().remove(data);
                notifyDataSetChanged();
            }
        });
        offerAdapter.setOfferEndtime(deadline);
        jibaojicai.rvSecondCategory.addItemDecoration(divider);
        jibaojicai.rvSecondCategory.setLayoutManager(new LinearLayoutManager(context));
        jibaojicai.rvSecondCategory.setNestedScrollingEnabled(false);
        jibaojicai.rvSecondCategory.setAdapter(offerAdapter);
        offerAdapter.setDatas(entity.getDetails());//添加报价列表
        //groupBuyType== 2时为汇集采购不展示新增和最多只能新增5条数据布局信息
        if (groupBuyType.equals("2")) {
            jibaojicai.ivAdd.setVisibility(View.GONE);
            jibaojicai.addMessage.setVisibility(View.GONE);
        } else {
            jibaojicai.ivAdd.setVisibility(View.VISIBLE);
            jibaojicai.addMessage.setVisibility(View.VISIBLE);
            if (null != entity.getPriceRule() && entity.getPriceRule().size() > 0) {
                if (entity.getPriceRule().size() == 5) {
                    jibaojicai.ivAdd.setBackground(context.getResources().getDrawable(R.drawable.add_gray));
                } else {
                    jibaojicai.ivAdd.setBackground(context.getResources().getDrawable(R.drawable.add_bright));
                }
            }
            jibaojicai.ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entity.getDetails().size() == 5) {
                        ToastUtil.show(context, "最多只能新增5条数据");
                    } else {
                        OfferGroupBuyingDetailsEntity.GroupBuyingDetails priceRule = entity.getDetails().get(entity.getDetails().size() - 1);
                        if (!TextUtils.isEmpty(priceRule.getSupplyTimeStart()) &&!TextUtils.isEmpty(priceRule.getSupplyTime()) && !TextUtils.isEmpty(priceRule.getStock()) && !TextUtils.isEmpty(priceRule.getPrice())) {
                            entity.getDetails().add(new OfferGroupBuyingDetailsEntity.GroupBuyingDetails());
                            notifyDataSetChanged();
                        } else {
                            if (TextUtils.isEmpty(priceRule.getSupplyTimeStart())||TextUtils.isEmpty(priceRule.getSupplyTime()) || TextUtils.isEmpty(priceRule.getStock()) || TextUtils.isEmpty(priceRule.getPrice())) {
                                MToast.showToast(context, "请完善报价信息");
                            }
                        }
                    }
                }
            });
        }
    }

    //时间选择
    private void showCourseTimePop(TextView tvTime, OfferGroupBuyingDetailsEntity.GroupBuyingDetails entity) {
        if (deadline < 100) {//时间戳
            dayCalendar.setTime(new Date());
        } else {
            dayCalendar.setTime(TimeUtil.getDateFromFormatString(TimeUtil.getDateStringYMD(deadline)));//非商品的入场时间和结束时间需在报价截止时间后
        }

        dayCalendar.add(Calendar.DAY_OF_MONTH, 0);
        TimePickerView timePicker = new TimePickerBuilder(context, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                tvTime.setText(format);
                selectedDate.setTime(date);
                entity.setSupplyTime(String.valueOf(TimeUtil.getLongTime(format, "yyyy-MM-dd")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(dayCalendar, null)
//                .setRangDate(null, null)//不限起始和结束时间
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    public void setItemCallBack(ItemCallBack itemCallBack) {
        this.itemCallBack = itemCallBack;
    }

    public void setOfferEndtime(long deadline) {
        this.deadline = deadline;
    }

    public interface ItemCallBack {
        void goPriceRole(OfferGroupBuyingDetailsEntity.GroupBuyingDetails groupBuyingDetails, TextView textView, int index);
    }


}
